class MyEventEmitter {
    constructor() {
        this._events = Object.create(null)
    }

    on(type, callback) {
        // 判断缓存中是否已近存在
        const event = this._events[type]
        if (event) {
            event.push(callback)
        } else {
            this._events[type] = [callback]
        }
    }

    emit(type, ...args) {
        const event = this._events[type]
        if (event && event.length) {
            event.forEach(callback => {
                callback.call(this, ...args)
            })
        }
    }

    off(type, callback) {
        const event = this._events[type]
        if (event && event.length) {
            this._events[type] = event.filter(fn => {
                return fn !== callback
            })
        }
    }

    once(type, callback) {
        const fn = (...args) => {
            callback.call(this, ...args)
            this.off(type, fn)
        }
        this.on(type, fn)
    }
}

const myEvent = new MyEventEmitter()

myEvent.on('message', () => {
    console.log('我被触发了', this)
})

myEvent.emit('message')

const fn = () => {
    console.log(111)
}
myEvent.on('aa', fn)
myEvent.emit('aa')
myEvent.off('aa', fn)
myEvent.emit('aa')

const fn1 = () => {
    console.log(222)
}

myEvent.once('bb', fn1)
myEvent.emit('bb')
myEvent.emit('bb')
